import { Injectable } from '@angular/core'
import { UsergridQuery } from '../../libs/usergrid-query'
@Injectable()
export class CursorService {
  public readonly dataSet = []
  public limit = 10
  public cursor = ''
  public statement = 'select *'
  public hasNextCursor = true
  public queryBuilder: UsergridQuery

  getConfig() {
    return {
      cursor: this.cursor,
      limit: this.limit,
      statement: this.queryBuilder ? this.queryBuilder.toString() : this.statement
    }
  }

  public query({ reset = false } = {}) {
    if (!this.queryBuilder || reset) {
      this.queryBuilder = new UsergridQuery()
    }

    return this.queryBuilder
  }

  public update({ cursor, hasNext }) {
    this.cursor = cursor
    this.hasNextCursor = hasNext
  }

  public get hasPrev() {
    return this.dataSet.length > 0
  }

  public get hasNext() {
    return !!this.cursor && this.hasNextCursor === true
  }

  /**
   * 读取下一个光标数据
   */
  public next(data) {
    this.dataSet.push({
      cursor: this.cursor,
      data
    })
  }

  /**
   * 返回前一个光标数据
   */
  public prev() {
    const { cursor, data } = this.dataSet.pop()
    this.cursor = cursor
    this.hasNextCursor = true
    return data
  }

  /**
   * 重置光标服务
   */
  public reset() {
    this.dataSet.length = 0
    this.limit = this.limit
    this.cursor = ''
    this.statement = 'select *'
    this.hasNextCursor = true
  }
}
